package com.yyh.sml;


import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;

public class Demo2 {
    public static void main(String[] args) throws IOException {
        //创建文档对象
        Document document = DocumentHelper.createDocument();
        //添加根标签
        Element rootElement = document.addElement("books");
        //根标签中添加子节点
        Element element = rootElement.addElement("book");
        //添加属性
        element.addAttribute("id","b002");
        //添加name标签
        Element element1 = element.addElement("name");
        element1.setText("java从入门到高级");
        //添加author标签
        Element element2 = element.addElement("author");
        element2.setText("马里奥");
        //添加price标签
        Element element3 = element.addElement("price");
        element3.setText("89.8");
        //将文档写入到文件中
        //创建解析对象
        OutputFormat prettyPrint = OutputFormat.createPrettyPrint();
        //创建写入的格式对象
        prettyPrint.setEncoding("utf-8");
        XMLWriter xmlWriter = new XMLWriter(new FileWriter("D:\\ideaproject\\IO-code\\XML-code\\src\\com\\yyh\\sml\\Books2\\Books.xml"),prettyPrint);
        //写入文档对象到文件中
        xmlWriter.write(document);
        //关闭流
        xmlWriter.close();
    }
}
